#-------------------------------------------------------------------------------
# Name:        html5_converter.py
# Purpose:     Generate HTML5 from SlideSpeech script
#
# Authors:     John Graves <john.graves@slidespeech.com>
#
# Copyright:   (c) Slidespeech Ltd 2012
# Licence:     MIT license
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import codecs, os, shutil, sys
import qar_to_audio_converter
from converter import Converter

from jinja2 import Environment, FileSystemLoader
import gettext
import jinja2.ext

class HTML5Converter(Converter):
    def __init__(self, templateDir, previous=None):
        Converter.__init__(self, previous)
        self._templateDir = templateDir

    def _convertImpl(self):

        tmp = self.tempDir()
        audioDir = os.path.join(tmp, "audio")
        imagesDir = os.path.join(tmp, "images" + os.sep + "CONTENTS")

        htmlDir = os.path.join(self.tempDir(), "html")
        try:
            shutil.rmtree(htmlDir)
        except OSError:
            # dir already cleared, shouldn't happen
            pass

        # make copy of template directory into htmlDir
        shutil.copytree(self._templateDir,htmlDir)

        # FIXME get language from config
        language = 'en'

        env = Environment(loader=FileSystemLoader(self._templateDir), extensions=['jinja2.ext.i18n'])
        domain = 'slidespeech'
        try:
            trans = gettext.translation(domain, os.path.join(os.getcwd(), 'locale'), [language])
        except IOError:
            # This probably means that there is no .mo file.
            # FIXME: This needs to be generated during installation
            trans = gettext.NullTranslations()

        env.install_gettext_translations(trans)

        try:
            seq = self.script()['S']

            slideSeq = []
            for slideNumber, slide in enumerate(seq):
                slide['number'] = slideNumber
                if 'c' in slide:
                    slide['questionNumber'] = "{0}q{1}".format(slide['n'],slide['c'])
                if 'A' in slide:
                    for i, answer in enumerate(slide['A']):
                        answer['responseNumber'] = i + 1
                slideSeq.append(slide)

            template = env.get_template('main_index.html')
            indexStr = template.render(LANGUAGE=language,
                                       slideCount=len(slideSeq),
                                       slideSeq=slideSeq,
                                       ttsURL=qar_to_audio_converter.AudioConfig.ttsURL,
                                       ttsEngine=qar_to_audio_converter.AudioConfig.ttsEngine
                                       )
            f = codecs.open(os.path.join(htmlDir, 'index.html'),
                            encoding='utf-8', mode='w+')
            f.write(indexStr)
            f.close()

            # copy the images and audio
            def visit(arg, dirname, names):
                for name in names:
                    if not os.path.isdir(os.path.join(dirname, name)):
                        shutil.copy(os.path.join(dirname, name), os.path.join(arg, name))

            os.path.walk(imagesDir, visit, htmlDir)
            os.path.walk(audioDir, visit, htmlDir)

        except KeyError as e:
            ex = ConverterError(_("Field missing in slide script"), e)
            raise ex

        os.remove(os.path.join(htmlDir,'main_index.html'))
